import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;

/**
 * User: Ryan Green
 * Date: Nov 5, 2010
 * Time: 12:51:28 PM
 * Copyright - University of South Australia
 */

//The class to hold all configuration
public class Config {
	public String serverAddress;

	public String watchFolder;
	public String watchFilter;

	public Config(String configFilename, LogHandler log) {
		try {

			//load the following from an xml config file   (configFilename)
			File fXmlFile = new File(configFilename);
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
			Document doc = dBuilder.parse(fXmlFile);
			doc.getDocumentElement().normalize();

			//get the root element
			Node nud = doc.getDocumentElement();
			serverAddress = getTagValue("serverAddress", (Element) nud);

			watchFolder = getTagValue("watchFolder", (Element) nud);
			if (getTagValue("watchFilter", (Element) nud) == null) {
				watchFilter = "";
			} else {
				watchFilter = getTagValue("watchFilter", (Element) nud);
			}

		} catch (Exception e) {
			log.Log("An error occurred when parsing the configuration file.", true);
			log.LogAndExit(e.getStackTrace());
		}
	}

	private static String getTagValue(String sTag, Element eElement) {
		Node nud = eElement.getElementsByTagName(sTag).item(0);

		if (nud == null) return null;

		return nud.getChildNodes().item(0).getNodeValue();
	}

}
